﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using BaseProject.Application.Implementation;
using BaseProject.Application.Interfaces;
using BaseProject.Domain.Configs;
using BaseProject.Domain.Repositories;
using BaseProject.Infrastructure.Data;
using BaseProject.Repositories;
using BaseProject.Validators;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Sakura.AspNetCore.Mvc;

namespace BaseProject.Web
{
    public class Startup
    {
        public IConfigurationRoot Configuration { get; }

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            if (env.IsDevelopment())
            {
                builder.AddApplicationInsightsSettings(developerMode: true);
            }

            Configuration = builder.Build();
        }
        
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthorization(options =>
            {
                //options.AddPolicy(Const.CONTRACTPolicy,
                //    policy =>
                //    {
                //        policy.Requirements.Add(new QKPermissionRequirement());
                //    });
            })
            .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.AccessDeniedPath = "/Account/Forbidden/";
                options.LoginPath = "/User/Login";
                options.ExpireTimeSpan = TimeSpan.FromHours(8);
                options.SlidingExpiration = false;
            });
            services.AddDirectoryBrowser();
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(30);
            });

            services.Configure<AppSettingConfig>(Configuration.GetSection("AppSettings"));
            services.Configure<ConnectionStringConfig>(Configuration.GetSection("ConnectionStrings"));

            services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssembly(typeof(RegisterViewModelValidator).GetTypeInfo().Assembly));
            services.AddAutoMapper();
            services.AddOptions();

            //分页组件
            services.AddBootstrapPagerGenerator(options =>
            {
                options.ConfigureDefault();
            });

            // Loading the "pager" section in the config file and set as the default pager options.
            //services.Configure<PagerOptions>(Configuration.GetSection("Pager"));

            services.AddElm(elmOptions =>
            {
                elmOptions.Filter = (loggerName, loglevel) => loglevel == LogLevel.Debug;
            });

            //注入
            services.AddTransient<IUserRepository, UserRepository>();
            services.AddTransient<IAuthenticationService, FormsAuthenticationImpl>();
            services.AddTransient<IWorkContext, WebWorkContext>();
            services.AddTransient<IUserService, UserServiceImpl>();

            //数据库链接
            Database.MASTER_LOCAL_CONNECTION = Configuration.GetConnectionString("MasterDbConnection");
            Database.SLAVE_LOCAL_CONNECTION = Configuration.GetConnectionString("SlaveDbConnection");
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var minutes = Configuration.GetSection("AppSettings").GetValue<int>("CookieExpiredMinutes");
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            loggerFactory.AddNLog();
            loggerFactory.AddConsole();

            app.UseApplicationInsightsRequestTelemetry();
            app.UseSession(new SessionOptions() { IdleTimeout = TimeSpan.FromMinutes(minutes) });
            app.UseStaticFiles();
            app.UseAuthentication();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Page/Error");
            }

            app.UseStatusCodePagesWithRedirects("~/Page/NotFound");

            app.UseElmPage();

            app.UseElmCapture();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
